var urls = {
    setHeadPortrait: '/front/user/_set-hp',
    currentUser: '/front/user/current'
};
window.layModules = {};

function ImageForm() {
    this.init();
}

ImageForm.prototype = {
    init: function () {
        var _this = this;
        this.imageHeadPortrait = $('#image-head-portrait');
        this.inputHeadPortrait = $('#input-hp');
        this.imageHeadPortrait.click(function () {
            _this.inputHeadPortrait.click();
        });
        this.inputHeadPortrait.change(function (e) {
            var filename = this.value;
            if (/^.*\.(jpg|bmp|png)$/.test(filename)) {
                _this.readImage();
            } else {
                layModules.layer.msg('仅支持[jpg,bmp,bmp]格式的图片');
                e.preventDefault();
                return false;
            }
        });
        this.form = $('#form-user-head');
        this.form.on('submit', function (e) {
            e.preventDefault();
            _this.uploadImage();
            return false;
        });
        this.loadUserImage();
    },
    loadUserImage: function () {
        var _this = this;
        $.get(urls.currentUser, function (res) {
            if (res.code === 0) {
                var user = res.data;
                if (user.headPortrait) {
                    _this.imageHeadPortrait.attr('src', user.headPortrait);
                }
            } else {
                layModules.layer.msg(res.msg);
            }
        }, 'json');
    },
    readImage: function () {
        var _this = this;
        var input = this.inputHeadPortrait[0];
        var file = input.files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (ev) {
            _this.onImageLoad(ev.target.result);
        }
    },
    onImageLoad: function (dataUrl) {
        this.imageHeadPortrait.attr('src', dataUrl);
    },
    uploadImage: function () {
        var fd = new FormData(this.form[0]);
        if (fd.get('hpFile').size === 0) {
            layModules.layer.msg('请选择图片');
            return;
        }
        var loadingIndex = layModules.layer.load(1);
        $.ajax({
            url: urls.setHeadPortrait,
            type: 'post',
            data: fd,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function (res) {
                if (res.code === 0) {
                    layModules.layer.msg('保存成功');
                } else {
                    layModules.layer.msg(res.msg);
                }
            },
            complete: function () {
                layModules.layer.close(loadingIndex);
            }
        });
    }
};
$(function () {
    function onLoad() {
        new ImageForm();
    }

    layui.use(['layer'], function () {
        layModules.layer = layui.layer;
        onLoad();
    });
});